﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Table = FCNS.Data.Table;
using DoubleH.Utility;
using System.Windows.Interop;
using DoubleH.Utility.Configuration;
using System.Diagnostics;
//using POS.Plugins;
using FCNS.Data;
using System.Collections.ObjectModel;
using System.Data.SQLite;
using System.Data;
using System.Reflection;

namespace POS
{
    public partial class MainWindow : Window
    {
        ObservableCollection<Table.PosOrderS> guaDanList = new ObservableCollection<Table.PosOrderS>();

        Table.UserS zengSongUserS = null;
        Int64 zengSongUserSId = -1;

        #region 模板相关 Login,Sale,Pay
        List<TempleteDefine> allTemplete = new List<TempleteDefine>();
        public List<TempleteDefine> AllTemplete
        {
            get { return allTemplete.FindAll(f => f.PosFlag == App.Pos.Flag); }
        }

        TempleteDefine currentTemplete = null;
        ILoginTemplete pLogin = null;
        static IPayTemplete pPay = null;
        static ISaleTemplete pSale = null;

        private void InitTemplete()
        {
            allTemplete.Add(new TempleteDefine() { Name = "StoreTemplete", Text = "便利店", PosFlag = Table.PosS.EnumFlag.零售, IsTouch = false });
            allTemplete.Add(new TempleteDefine() { Name = "TouchTemplete", Text = "便利店(触摸屏)", PosFlag = Table.PosS.EnumFlag.零售, IsTouch = true });
            allTemplete.Add(new TempleteDefine() { Name = "WuJinTemplete", Text = "五金", PosFlag = Table.PosS.EnumFlag.五金, IsTouch = true });
        }

        private void LoadTemplete()
        {
            currentTemplete = allTemplete.FirstOrDefault(f => f.PosFlag == App.Pos.Flag && f.Name == DoubleHConfig.AppConfig.PosTempleteName);
            if (currentTemplete == null)
                currentTemplete = allTemplete.FirstOrDefault(f => f.PosFlag == App.Pos.Flag);

            Debug.Assert(currentTemplete != null, "模板丢失");
            switch (currentTemplete.PosFlag)
            {
                case Table.PosS.EnumFlag.零售:
                    {
                        switch (currentTemplete.Name)
                        {
                            case "TouchTemplete":
                                pLogin = new Templete.TouchTemplete.PageLogin();
                                pSale = new Templete.TouchTemplete.PageSale();
                                pPay = new Templete.TouchTemplete.PagePay();
                                break;
                            default:
                                pLogin = new Templete.StoreTemplete.PageLogin();
                                pSale = new Templete.StoreTemplete.PageSale();
                                pPay = new Templete.StoreTemplete.PagePay();
                                break;
                        }
                    }
                    break;

                case Table.PosS.EnumFlag.五金:
                    pLogin = new Templete.WuJinTemplete.PageLogin();
                    pSale = new Templete.WuJinTemplete.PageSale();
                    pPay = (IPayTemplete)pSale;
                    break;
            }

            Debug.Assert(pLogin != null);
            Debug.Assert(pSale != null);
            Debug.Assert(pPay != null);
            ChangeUI(EnumUI.登陆);

            pLogin.Logined += (user, mode) => Logined(user, mode);

            pSale.Saled += new dSaleToPayEvent(Saled);
            pSale.ZengSong += new dZengSong(pSale_ZengSong);
            pSale.EditProduct += new dEditProduct(pSale_EditProduct);
            pSale.JiaoBan += new dNoParams(pSale_JiaoBan);
            pSale.GuaDan += new dGuaDan(pSale_GuaDan);
            pSale.TuiHuo += new dNoParams(ChangeMode);
            pSale.StoreS = Table.StoreS.GetObject(App.Pos.StoreSId);

            pPay.Payed += (ss, ee) => Payed(ss, ee);
        }

        private void Logined(Table.UserS ss, EnumMode ee)
        {
            if (DateTime.Now.Date < Table.SysConfig.SysConfigParams.LastLoginDate.Date)
            {
                if (Table.SysConfig.SysConfigParams.ForceVerificationDate)
                {
                    MessageWindow.Show("当前日期小于上一次登录的日期,禁止登录.");
                    return;
                }
                if (MessageWindow.Show("", "当前日期小于上一次登录的日期：" + Table.SysConfig.SysConfigParams.LastLoginDate.ToLongDateString() + "，继续吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;//还要检查是否月结日
            }
            if (!IsCurrentShift(ss))
                return;

            Table.UserS.LoginUser = ss;
            //以下内容必须放这里,因为如果用户没登陆,初始化DataGridColumns就会出错,它是调去用户配置文件的.
            DoubleHConfig.UserConfig = ConfigSerializer.LoadUserConfig(Table.UserS.LoginUser.Id);
            labelUserName.Content = Table.UserS.LoginUser.Name;
            pSale.Init();
            //Table.ErrorS.WriteLogFile(ss._LoginName + " 登陆成功");
            App.Pos.UpdateLastLoginDateTime(DateTime.Now);
            App.Mode = ee;
            labelSaleMode.Content = ee.ToString();
            ChangeUI(EnumUI.零售);
        }

        private void Saled()
        {
            Debug.Assert(App.Order != null);

            App.Order._UserSName = Table.UserS.LoginUser._LoginName;//新增的pos订单还没有用户名，此操作是为了打印的时候会显示用户名。
            ChangeUI(EnumUI.结账);
        }

        private void Payed(double money, bool isPayed)
        {
            if (isPayed)
            {
                SaveOrder(money);
                DoubleH.Utility.PrintFunction.PrintPosOrder(App.Order);

                pSale.OrderFinish(App.Order);
                App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                ChangeUI(EnumUI.零售);

                zengSongUserS = null;
                zengSongUserSId = -1;
            }
            else
                frame1.Navigate(pSale);
        }

        private void SaveOrder(double money)
        {
            App.Order.PosNO = App.Pos.PosNO;
            App.Order.StoreSId = App.Pos.StoreSId;
            App.Order.ZengSongUserSId = zengSongUserSId;
            if (App.Mode == EnumMode.退货模式)
            {
                Table.DataTableS.EnumDatabaseStatus result = App.Order.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    DoubleHConfig.AppConfig.PosCashboxMoney = DoubleHConfig.AppConfig.PosCashboxMoney - App.Order.Money;
                else
                    MessageWindow.Show(result.ToString());

                App.Mode = EnumMode.零售模式;
                labelSaleMode.Content = App.Mode;
            }
            else
            {
                Table.DataTableS.EnumDatabaseStatus result = App.Order.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    DoubleHConfig.AppConfig.PosCashboxMoney += App.Order.Money;
                else
                    MessageWindow.Show(result.ToString());
            }
        }

        private bool IsCurrentShift(Table.UserS newUser)
        {
            //检查交班状态
            App.CurrentShift = Table.PosShiftS.GetObjectNotShift(DoubleHConfig.AppConfig.PosNO);
            Table.UserS user = newUser;
            if (App.CurrentShift == null)
            {
                JiaoBanWindow jb = new JiaoBanWindow();
                jb.Init(true, false);
                jb.ShowDialog();
                if (!jb.Ensure)
                    return false;

                Table.PosShiftS pss = new Table.PosShiftS();
                pss.PosNO = DoubleHConfig.AppConfig.PosNO;
                pss.UserSId = user.Id;
                pss.StartDateTime = DateTime.Now;
                pss.StartMoney = jb.doubleUpDownMoney.Value.Value;
                pss.Insert();
                App.CurrentShift = pss;
            }
            else
            {
                if (user.Id != App.CurrentShift.UserSId)
                    if (MessageWindow.Show("", App.CurrentShift._UserSName + " 尚未交班,是否继续?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                        return false;
            }
            return true;
        }

        #endregion

        #region 接口相关
        private void pSale_GuaDan(bool isTemp, bool addOrRemove, string flag)
        {
            if (isTemp)
                GuaDanIsTemp(addOrRemove, flag);
            else
                GuaDanNotTemp(addOrRemove, flag);

            pSale.GuaDanFinish(guaDanList);
        }
        private void GuaDanIsTemp(bool addOrRemove, string flag)
        {
            if (addOrRemove)
            {
                Debug.Assert(App.Order != null);

                if (guaDanList.FirstOrDefault(f => f._CorSVipNO == App.Vip.VipNO) != null)
                {
                    MessageWindow.Show("当前客户已存在挂单,不能再添加.");
                    return;
                }
                if (App.Vip != null)
                    App.Order._CorSVipNO = App.Vip.VipNO;

                guaDanList.Add(App.Order);
                App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                pSale.InitOrder();
                MessageWindow.Show("挂单成功");
            }
            else
            {
                App.Order = guaDanList.FirstOrDefault(f => f._CorSVipNO == flag);
                if (App.Order == null)
                {
                    int index = -1;
                    if (Int32.TryParse(flag, out index) && index >= 0 && index < guaDanList.Count)
                        App.Order = guaDanList[index];
                }

                if (App.Order != null)
                    guaDanList.Remove(App.Order);
                else
                {
                    MessageWindow.Show("挂单提取失败");
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                }

                pSale.InitOrder();
            }
        }
        private void GuaDanNotTemp(bool addOrRemove, string flag)
        {
            if (addOrRemove)
            {
                Table.DataTableS.EnumDatabaseStatus result;
                if (App.Order.CorSId == -1)
                {
                    MessageWindow.Show("客户不能为空");
                    return;
                }

                if (App.Order.Id == -1)
                {
                    App.Order.PosNO = App.Pos.PosNO;
                    App.Order.StoreSId = App.Pos.StoreSId;
                    App.Order.Enable = Table.PosOrderS.EnumEnable.记账;
                    result = App.Order.Insert();
                }
                else
                    result = App.Order.Update();

                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                {
                    MessageWindow.Show("挂单成功");
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                    pSale.InitOrder();
                }
                else
                    MessageWindow.Show(result.ToString());
            }
            else
                MessageWindow.Show("已记账单据禁止编辑");
        }

        private void pSale_JiaoBan()
        {
            if (Table.UserS.LoginUser == null)
                return;

            if (App.CurrentShift.UserSId != Table.UserS.LoginUser.Id)
            {
                MessageWindow.Show("当前班次属于 " + App.CurrentShift._UserSName + " 请重新登陆.");
                return;
            }
            if (MessageWindow.Show("", "确认交班吗?", MessageBoxButton.YesNo) == MessageBoxResult.No)
                return;

            JiaoBanWindow jb = new JiaoBanWindow();
            jb.Init(false, false);
            jb.ShowDialog();
            if (jb.Ensure)
            {
                if (DoubleHConfig.AppConfig.PosIsPrintJiaoBan)
                {
                    PrintFunction.PrintPosJiaoBan(Table.UserS.LoginUser._LoginName, App.CurrentShift.PosNO, jb.doubleUpDownMoney.Value.Value.ToString(), jb.labelMoneySum.Content.ToString());
                }
                LogOff(false);
            }
        }

        private void pSale_ZengSong()
        {
            if (zengSongUserS == null && App.Order.ZengSongList.Count == 0)
                StartZengSong();
            else
                EndZengSong();
        }
        private void StartZengSong()
        {
            Debug.Assert(zengSongUserS == null);

            if (App.Mode != POS.EnumMode.零售模式)
            {
                MessageWindow.Show("退货模式不可赠送");
                return;
            }
            if (App.Order.ZengSongList.Count > 0)
            {
                MessageWindow.Show("一张单据只能做一次赠送");
                return;
            }

            DoubleH.Utility.TextInputWindow tiw = new TextInputWindow();
            tiw.Init("格式：账号.密码（例如:001.000000）", null, true);
            tiw.ShowDialog();
            string tiwText = tiw.Text;
            if (string.IsNullOrEmpty(tiwText) || !tiwText.Contains("."))
            {
                MessageWindow.Show("输入错误");
                return;
            }

            int index = tiwText.IndexOf('.', 0);
            zengSongUserS = Table.UserS.GetObject(tiwText.Substring(0, index), tiwText.Substring(index + 1));
            if (zengSongUserS == null || !zengSongUserS.HasAuthority(Table.PosS.EnumAuthority.赠送.ToString(), Table.UserS.EnumAuthority.查看))
            {
                MessageWindow.Show("权限不足");
                zengSongUserS = null;
                return;
            }

            MessageWindow.Show("赠送开始，重复点击可以结束赠送");
        }
        private void EndZengSong()
        {
            if (zengSongUserS == null)
                return;

            zengSongUserSId = zengSongUserS.Id;
            zengSongUserS = null;
            MessageWindow.Show("赠送结束");
        }

        private void pSale_EditProduct(EnumEditProduct eep, Table.ProductS product, double quantity, double price)
        {
            if (product == null)
            {
                MessageWindow.Show("请选择商品");
                return;
            }

            switch (eep)
            {
                case EnumEditProduct.添加: EditProductAdd(product); break;
                case EnumEditProduct.移除: EditProductRemove(product); break;
                case EnumEditProduct.编辑数量: EditProductQuantity(product, quantity); break;
                case EnumEditProduct.编辑价格: EditProductPrice(product, price); break;
            }
        }
        private void EditProductAdd(Table.ProductS product)
        {
            if (zengSongUserS != null)
            {
                Table.ProductS zsps = product.CloneObject(null) as Table.ProductS;
                Debug.Assert(zsps != null);
                zsps.Name += "(赠送)";
                zsps._TempPrice = 0;
                App.Order.ProductSList.Add(zsps);

                Table.ProductSInZengSongS zs = new Table.ProductSInZengSongS()
                {
                    ProductSId = product.Id,
                    Quantity = product._TempQuantity,
                    AveragePrice = product._AveragePrice
                };
                App.Order.ZengSongList.Add(zs);
                zsps._Tag = zs;//仅用于标识
            }
            else
            {
                product.InitPrice(App.Vip);
                App.Order.ProductSList.Add(product);
            }
        }
        private void EditProductRemove(Table.ProductS product)
        {
            if (zengSongUserS != null)
            {
                Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
                Table.ProductS pzs = App.Order.ProductSList.FirstOrDefault(f => f._Tag == zs);
                Debug.Assert(pzs != null);

                App.Order.ProductSList.Remove(pzs);
                App.Order.ZengSongList.Remove(zs);
            }
            else
            {
                if (product._Tag == null)
                    App.Order.ProductSList.Remove(product);
                else
                    MessageWindow.Show("非赠送模式下禁止移除赠品");
            }
        }
        private void EditProductQuantity(Table.ProductS product, double quantity)
        {
            Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
            if (zengSongUserS != null)
            {
                Table.ProductS pzs = App.Order.ProductSList.FirstOrDefault(f => f._Tag == zs);
                pzs._TempQuantity = quantity;
                zs.Quantity = quantity;
            }
            else
            {
                if (product._Tag == null)
                    product._TempQuantity = quantity;
                else
                    MessageWindow.Show("非赠送模式下禁止编辑数量");
            }
        }
        private void EditProductPrice(Table.ProductS product, double price)
        {
            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.更改零售价) == Table.UserS.EnumAuthority.无权限)
            {
                MessageWindow.Show("权限不足");
                return;
            }

            Table.ProductSInZengSongS zs = App.Order.ZengSongList.FirstOrDefault(f => f.ProductSId == product.Id);
            if (zengSongUserS != null || product._Tag != null)
                MessageWindow.Show("赠送商品不能编辑价格");
            else
            {
                if (price <= 0)
                    MessageWindow.Show("价格必须大于 0");
                else
                    product._TempPrice = price;
            }
        }
        #endregion

        #region 离线模式的上传下载数据

        SQLiteConnection conSqlite;
        SQLiteCommand cmdSqlite;
        System.Threading.Thread thread = null;

        private void StartOfflineData()
        {
            thread = new System.Threading.Thread(StartUploadData);
            thread.Start();
        }

        private void StartUploadData()
        {
            if (FCNS.Data.DbDefine.dbFile == FCNS.Data.SQLdata.SqlConfig.Db)
            {
                onlineMode.Dispatcher.Invoke(
new Action(() => onlineMode.Content = "单机模式"));
                return;
            }

            //如果上传不成功就不要下载数据了,因为上传数据完成后会清空数据库所有报表.如果不这样,当数据表列有变动的时候就无法实时更新了.
            LoadLocalDbFile();
            if (CheckVersion())
                UploadData();

            conSqlite.Close();
            cmdSqlite.Dispose();
            conSqlite.Dispose();
            thread.Abort();
        }
        /// <summary>
        /// 一定要把数据下载放在软件关闭的时候,这样可以及时更新交班情况.
        /// </summary>
        private void StartDownloadData()
        {
            if (FCNS.Data.DbDefine.dbFile == FCNS.Data.SQLdata.SqlConfig.Db)
                return;

            LoadLocalDbFile();
            DownloadData();

            conSqlite.Close();
            cmdSqlite.Dispose();
            conSqlite.Dispose();
        }

        private bool CheckVersion()
        {
            cmdSqlite.CommandText = "select Ver from SysConfig";
            string ver = cmdSqlite.ExecuteScalar() as string;
            if (ver == Table.SysConfig.SysConfigParams.Ver)
                return true;

            MessageWindow.Show("POS端数据库版本不一致,点击确定后升级.");
            ProcessStartInfo info = new ProcessStartInfo();
            info.Arguments = "pos";
            info.FileName = FCNS.Data.DbDefine.baseDir + "Update.exe";
            Process.Start(info);
            System.Environment.Exit(0);
            return false;
        }

        /*
         * 因为只有在线模式下才会上传/下载数据
         *所以 POS.exe 使用的肯定是在线的数据库
         *那么 uad.exe 使用的就是离线状态的数据库文件了
         */
        private void UploadData()
        {
            //通过 PosS 表中保存的最后更新的数据Id号来标识
            //PosOrderS
            DataTable tableOrder = new DataTable("PosOrderS");
            DataTable tableShift = new DataTable("PosShiftS");
            DataTable tableZengSong = new DataTable("ProductSInZengSongS");
            DataTable tableProductSIO = new DataTable("ProductSIO");
            #region //加载数据
            SQLiteDataAdapter adapter = new SQLiteDataAdapter("select * from PosOrderS where Id>" + App.Pos.LastUpdatePosOrderSId, conSqlite);
            try
            {
                adapter.Fill(tableOrder);
            }
            catch (Exception ee)
            {
                MessageWindow.Show("PosOrderS 上传失败" + ee.Message);
                adapter.Dispose();
                return;
            }

            //PosShiftS
            try
            {
                adapter.SelectCommand.CommandText = "select * from PosShiftS where Id>" + App.Pos.LastUpdatePosShiftSId;
                adapter.Fill(tableShift);
            }
            catch (Exception ee)
            {
                MessageWindow.Show("PosShiftS 上传失败" + ee.Message);
                adapter.Dispose();
                return;
            }
            //ProductSInZengSongS
            try
            {
                adapter.SelectCommand.CommandText = "select * from ProductSInZengSongS where RelatedOrderNO in (select OrderNO from PosOrderS where Id>" + App.Pos.LastUpdatePosOrderSId + ")";
                adapter.Fill(tableZengSong);
            }
            catch (Exception ee)
            {
                MessageWindow.Show("ProductSInZengSong 上传失败" + ee.Message);
                adapter.Dispose();
                return;
            }
            //ProductSIO
            try
            {
                adapter.SelectCommand.CommandText = "select * from ProductSIO where OrderNO in (select OrderNO from PosOrderS where Id>" + App.Pos.LastUpdatePosOrderSId + ")";
                adapter.Fill(tableProductSIO);
            }
            catch (Exception ee)
            {
                MessageWindow.Show("ProductSIO 上传失败" + ee.Message);
                adapter.Dispose();
                return;
            }

            adapter.Dispose();
            #endregion

            #region 转换数据
            Table.DataTableS.EnumDatabaseStatus result = Table.DataTableS.EnumDatabaseStatus.操作成功;
            foreach (DataRow row in tableShift.Rows)
            {
                Table.PosShiftS obj = Table.PosShiftS.RowToClass(row, false);
                MessageBox.Show((obj == null).ToString());
                if (obj == null)
                    continue;


                Int64 id = obj.Id;//必须要这样,因为Insert()后本地的Id值和远程Id值不一样
                result = obj.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    App.Pos.UpdateLastUpdatePosShiftSId(id);
                else
                    MessageWindow.Show(result.ToString());
            }

            ObservableCollection<Table.ProductSInZengSongS> allZengSong = new ObservableCollection<Table.ProductSInZengSongS>();
            foreach (DataRow row in tableZengSong.Rows)
            {
                Table.ProductSInZengSongS obj = Table.ProductSInZengSongS.RowToClass(row, false);
                if (obj != null)
                    allZengSong.Add(obj);
                //如果赠品记录无法读取完整，就不要继续读取零售单了。
            }
            ObservableCollection<Table.ProductSIO> allProductSIO = new ObservableCollection<Table.ProductSIO>();
            foreach (DataRow row in tableProductSIO.Rows)
            {
                Table.ProductSIO obj = Table.ProductSIO.RowToClass(row, false);
                if (obj != null)
                    allProductSIO.Add(obj);

                //如果赠品记录无法读取完整，就不要继续读取零售单了。
            }

            foreach (DataRow row in tableOrder.Rows)
            {
                Table.PosOrderS obj = Table.PosOrderS.RowToClass(row, false);
                if (obj == null)
                    continue;

                obj.ZengSongList = new ObservableCollection<Table.ProductSInZengSongS>(allZengSong.Where(f => f.RelatedOrderNO == obj.OrderNO));
                ObservableCollection<Table.ProductS> ps = new ObservableCollection<Table.ProductS>();
                foreach (Table.ProductSIO io in allProductSIO.Where(f => f.OrderNO == obj.OrderNO))
                {
                    Table.ProductS p2 = Table.ProductS.GetObject(io.ProductSId);
                    Debug.Assert(p2 != null);

                    p2._TempPrice = io.WholesalePrice;
                    p2._TempQuantity = io.Quantity;

                    ps.Add(p2);
                }
                obj.ProductSList = ps;

                Int64 id = obj.Id;
                result = obj.Insert();
                if (result == Table.DataTableS.EnumDatabaseStatus.操作成功)
                    App.Pos.UpdateLastUpdatePosOrderSId(id);
                else
                    MessageWindow.Show(result.ToString());
            }
            #endregion
        }

        private void DownloadData()
        {
            List<string> sqlStrings = new List<string>();
            //CorS 仅客户
            sqlStrings.Add("delete from CorS where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.CorS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from CorS where Enable=0 and (Flag=0 or Flag=2)")));
            //ProductS 仅POS所属仓库的商品
            sqlStrings.Add("delete from ProductS where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.ProductS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from ProductS where Enable=0 and (Flag=0 or Flag=1)")));
            //GroupS  仅客户和商品
            sqlStrings.Add("delete from GroupS where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.GroupS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from GroupS where Enable=0 and  (Flag=0 or Flag=1)")));
            //SysConfig
            sqlStrings.Add("delete from SysConfig where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.SysConfig.tableName, FCNS.Data.SQLdata.GetDataTable("select * from SysConfig")));
            //UserS  仅POS操作员
            sqlStrings.Add("delete from UserS where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.UserS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from UserS where Enable=0 and  Flag=2 ")));
            //UniqueS  仅 计量单位 = 0, 支付方式5， 品牌11,产地12,会员分类16, 商品属性17,
            sqlStrings.Add("delete from UniqueS  where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.UniqueS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from UniqueS where Enable=0 and (Flag=0 or Flag=5 or Flag=11 or Flag=12 or Flag=16 or Flag=17)")));
            //PosS
            sqlStrings.Add("delete from PosS  where Id<>-1");
            sqlStrings.AddRange(FormatObj(Table.PosS.tableName, FCNS.Data.SQLdata.GetDataTable("select * from PosS where Enable=0")));

            cmdSqlite.Parameters.Add(cmdSqlite.CreateParameter());
            System.Data.Common.DbTransaction trans = conSqlite.BeginTransaction();
            try
            {
                for (int i = 0; i < sqlStrings.Count; i++)
                {
                    cmdSqlite.CommandText = sqlStrings[i];
                    cmdSqlite.Parameters[0].Value = i.ToString();
                    cmdSqlite.ExecuteNonQuery();
                }
                trans.Commit();
            }
            catch (Exception ee)
            {
                MessageWindow.Show("远程数据库下载失败,请重启程序重试.\r\n" + ee.Message);
            }
        }

        private void LoadLocalDbFile()
        {
            conSqlite = new SQLiteConnection();
            cmdSqlite = new SQLiteCommand();
            //bool haveFile = System.IO.File.Exists(FCNS.Data.DbDefine.dbFile);//如果离线模式下数据文件丢失了,这样可以新建一个.有必要吗?先留着了.
            SQLiteConnectionStringBuilder connstr = new SQLiteConnectionStringBuilder();
            connstr.DataSource = FCNS.Data.DbDefine.dbFile;
            conSqlite.ConnectionString = connstr.ToString();
            conSqlite.Open();
            cmdSqlite.Connection = conSqlite;
            //if (!haveFile)
            //{
            //    List<string> ls = new List<string>();
            //    Assembly asm = Assembly.LoadFrom(FCNS.Data.DbDefine.baseDir + "FCNS.Data.dll");//读取嵌入式资源
            //    System.IO.TextReader reader = new System.IO.StreamReader(asm.GetManifestResourceStream("FCNS.Data.Script.sqlite.txt"));
            //    string str = string.Empty;
            //    while ((str = reader.ReadLine()) != null)
            //        ls.Add(str);

            //    reader.Dispose();
            //    foreach (string sss in ls)
            //    {
            //        cmdSqlite.CommandText = sss;
            //        cmdSqlite.ExecuteNonQuery();
            //    }
            //}
        }

        private List<string> FormatObj(string tableName, DataTable table)
        {
            List<string> result = new List<string>();
            foreach (DataRow row in table.Rows)
            {
                StringBuilder sbName = new StringBuilder("insert into " + tableName + "(");
                StringBuilder sbValue = new StringBuilder(" values (");
                foreach (DataColumn column in table.Columns)
                {
                    sbName.Append(column.ColumnName + ",");

                    if (column.DataType == typeof(string))
                        sbValue.Append("'" + row[column] + "',");
                    else
                        sbValue.Append(row[column] + ",");
                }

                sbName.Remove(sbName.Length - 1, 1);
                sbValue.Remove(sbValue.Length - 1, 1);
                sbName.Append(")");
                sbValue.Append(")");
                result.Add(sbName.ToString() + sbValue.ToString());
            }

            return result;
        }
        #endregion

        private void ChangeUI(EnumUI ui)
        {
            switch (ui)
            {
                case EnumUI.零售:
                    pSale.InitOrder();
                    frame1.Navigate(pSale);
                    break;

                case EnumUI.结账:
                    frame1.Navigate(pPay);
                    break;

                default:
                    frame1.Navigate(pLogin);
                    break;
            }
        }

        public void ChangeMode()
        {
            if (!(frame1.Content is ISaleTemplete))
                return;

            switch (App.Mode)
            {
                case EnumMode.零售模式:
                    if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.退货) == Table.UserS.EnumAuthority.无权限)
                    {
                        MessageWindow.Show("权限不足");
                        return;
                    }

                    App.Mode = EnumMode.退货模式;
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS退货单);
                    pSale.InitOrder();
                    break;

                case EnumMode.退货模式:
                    App.Mode = EnumMode.零售模式;
                    App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
                    pSale.InitOrder();
                    break;
            }
            labelSaleMode.Content = App.Mode;
        }

        private void OpenCashbox()
        {
            if (Table.UserS.LoginUser == null)
                return;
            if (Table.UserS.LoginUser.GetAuthority(Table.PosS.EnumAuthority.弹出钱箱) > Table.UserS.EnumAuthority.无权限)
            {
            }
            else
                MessageWindow.Show("权限不足");
        }

        private void CancelOrderByHotKey()
        {
            if (!(frame1.Content is ISaleTemplete))
                return;

            if (MessageWindow.Show("", "确定取消当前单据吗？", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                return;

            App.Mode = EnumMode.零售模式;
            labelSaleMode.Content = App.Mode;
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
            ChangeUI(EnumUI.零售);
        }

        public void LogOff(bool confirm)
        {
            if (confirm)
            {
                if ((frame1.Content is ILoginTemplete))
                    return;

                if (MessageWindow.Show("", "注销当前用户吗？", MessageBoxButton.YesNo) == MessageBoxResult.No)
                    return;
            }

            labelUserName.Content = "未登陆";
            labelSaleMode.Content = "";
            Table.UserS.LoginUser = null;
            App.Order = new Table.PosOrderS(Table.PosOrderS.EnumFlag.POS零售单);
            frame1.Navigate(pLogin);
        }

        public void CloseThis()
        {
            bool close = true;
            foreach (Window w in this.OwnedWindows)
                if (w.IsActive)
                {
                    w.Close();
                    return;
                }

            if (close)
                this.Close();
        }

        /// <summary>
        /// 强制交班,仅能 InitDateTime 调用
        /// </summary>
        private void ForceJiaoBanNow()
        {
            if (DoubleHConfig.AppConfig.PosJiaoBan != DateTime.Now.ToString("HHmm"))
                return;

            JiaoBanWindow jb = new JiaoBanWindow();
            jb.Init(false, true);
            jb.ShowDialog();
            if (DoubleHConfig.AppConfig.PosIsPrintJiaoBan)
                PrintFunction.PrintPosJiaoBan(Table.UserS.LoginUser._LoginName, App.CurrentShift.PosNO, jb.doubleUpDownMoney.Value.Value.ToString(), jb.labelMoneySum.Content.ToString());

            LogOff(false);
        }
    }
}